from django.shortcuts import render
from django.http import HttpResponse
from myadmin.models import Types,Goods,Order,Users,OrderInfo
# from . models import Citys
from django.contrib.auth.hashers import check_password

import json
import time
# 查询导航分类信息 查询所有的二级分类
def gettypeall():
    ob=Types.objects.exclude(pid=0)
    return ob
def index(request):
    #select yiji
    t = Types.objects.filter(pid=0)
    arr=[]
    for v in t:
        #select childobject
        v.sub = Types.objects.filter(pid = v.id)
        for x in v.sub:
            x.sub = Goods.objects.filter(typeid_id = x.id)
        arr.append(v)
    # 热品推荐
    ob = Goods.objects.all()
    # 热品推荐
    
    # arr = [
    #     {'name':'服装','sub':[{'name':'男装','sub':[{}]},{'name':'女装','sub':[{},{}]}]},
    #     {'name':'数码','sub':[{'name':'手机'}]}
    # ]


    # print(arr[0].sub[0].sub[0].title)

    context = {'typelist':gettypeall(),'typegoods':arr,'hotsale':ob}
    return render(request,'home/index.html',context)

def newindex(request):
    t = Types.objects.filter(pid=0)
    arr=[]
    for v in t:
        #select childobject
        v.sub = Types.objects.filter(pid = v.id)
        for x in v.sub:
            x.sub = Goods.objects.filter(typeid_id = x.id)
        arr.append(v)
    ob = Goods.objects.all()
    cart=request.session['VipUser']
    context = {'typelist':gettypeall(),'typegoods':arr,'hotsale':ob,'users':cart}
    return render(request,'home/newindex.html',context)
def lists(request,tid):
    a = int(request.GET.get('a',0))
   
    t = Types.objects.get(id=tid)
     # 判断当前分类是否为一级分类
    if t.pid == 0:
        # 如果是一级分类,则再查询当前分类下的子类
        t.sub = Types.objects.filter(pid=tid)
        t.md = t.id
        # 再查询子类下的商品信息
        for v in t.sub:
            if a :

                v.sub = Goods.objects.filter(typeid_id=v.id).filter(status=a).order_by('price')
            else:
                v.sub = Goods.objects.filter(typeid_id=v.id).order_by('price')
                
    else:
        # 二级分类
        # 查询当前分类下的商品
        t.md = t.pid
        if a :
            t.sub = Goods.objects.filter(typeid_id=t.id).filter(status=a).order_by('price')
        else:
            t.sub = Goods.objects.filter(typeid_id=t.id).order_by('price')
            
        t.pname = Types.objects.get(id = t.pid)
        t.siblings = Types.objects.filter(pid = t.pid).exclude(id=t.id)



    # 一级分类
    # {
    #     'name':'服装',
    #     'sub':[
    #           {'name':'男装','sub':[{},{}]},
    #           {'name':'女装','sub':[{},{}]}
    #         ]
    # }


    # 二级分类
    # {
    #     'name':'男装',
    #     'sub':[{},{}],
    #     'pname':{'name':'服装',id:1},
    #     'siblings':[{'name':'女装'}]
    # }


    # 判断当前是否有pname属性
    # if hasattr(t,'pname'):
    #     # 如果有pname 证明时二级类
    #     print(t.pname.name)
    #     print('二级类')
    # else:
    #     # 如果没有pname 证明时一级类
    #     print(t.name)
    #     print('一级类')


    context = {'typelist':gettypeall(),'lists':t}
    return render(request,'home/lists.html',context)

def goods(request,tid):
    ob = Goods.objects.get(id=tid)
    context={'ginfo':ob}
    return render(request,'home/goods.html',context)
    # return HttpResponse('ok')


# 处理购物车数据，
def cartadd(request):  
    gid = request.POST['gid']
    num = int(request.POST['num'])
    data = request.session.get('cart',{})

    if gid in data.keys():
        data[gid]['num'] += num
    else:
        goods=Goods.objects.get(id=gid)
        arr = {'title':goods.title,'id':goods.id,'price':float(goods.price),'pic':goods.pic,'num':num}
        data[gid] = arr
    '''
    data={
       6:{'id': 6, 'price': 99.9, 'pic': '/static/public/img/1523839869.9352133.jpg', 'num': '1', 'title': '红虎皮超短裙,配黑丝袜'},

       5:{}
    }

    '''

    # 设置session来标记该商品是否已添加入购物车，
    request.session['cart'] = data

    # return render(request,'home/cart.html')
    return HttpResponse('<script>alert("添加成功");location.href="/cartindex"</script>')
def cartindex(request):
    cart = request.session.get('cart')
    context={'cart':cart}
    return render(request,'home/cartindex.html',context)

# 修改购物车商品数量,to update session 'num',以便在生成订单界面获取id来加载购物车中对应的商品信息
def cartedit(request):
    gid = request.GET.get('gid',None)
    num = request.GET.get('num',None)

    # 获取购物车信息
    cart = request.session.get('cart',{})
    # 修改对应商品的数量
    cart[gid]['num']=int(num)

    request.session['cart']=cart
    return 
def cartdel(request):
    gid = request.GET.get('gid',None)
    print(gid)
    cart = request.session.get('cart',{})
    del cart[gid]
    request.session['cart'] = cart
    return HttpResponse('<script>alert("移除成功");location.href="/meizu/cartinsert"</script>')

# 订单确认,后面的一长条数据
def orderadd(request):
    # 选择购买的商品id
    ids = request.POST.get('ids','').split(',')
    # 购物车数据{6:{},5:{}}
    cart = request.session['cart']
    print(cart)
    # order整装所有的’值‘即后面的一长条数据
    order = []
    for x in ids:
        order.append(cart[x])
    print(order)
    context = {'orders':order,'ids':ids}
    return render(request,'home/orderconfirm.html',context)

# def orderconfirm(request):

#     return HttpResponse('OK')
   
# 生成订单,处理数据,将购买的商品信息等存入数据库
def ordercreate(request):
    ids = request.POST.get('ids','').split(',')
    cart = request.session['cart']
    totalprice = 0
    totalnum = 0
    for x in ids:
        totalprice +=(cart[x]['price']*cart[x]['num'])
        totalnum += cart[x]['num']
    
    # 先添加订单信息
    ob = Order()
    ob.uid = Users.objects.get(id=request.session['VipUser']['uid'])
    # 收货信息
    ob.addname = request.POST['addname']
    ob.address = request.POST['address']
    ob.addphone = request.POST['addphone']
    ob.addcode = request.POST['addcode']
    ob.totalprice = totalprice
    ob.totalnum = totalnum
    ob.status = 1
    ob.save()
    

    # 再去添加订单详情信息
    for x in ids:
        info = OrderInfo()
        info.orderid = ob
        info.gid = Goods.objects.get(id=x)
        info.num = cart[x]['num']
        info.price = cart[x]['price']
        info.save()
        # 提交订单后购物车中就没有该商品的信息了
        del cart[x]

    request.session['cart'] = cart
    # return HttpResponse('ok')
    # return  HttpResponse('<script>alert("下单成功");location.href="/myorder"</script>')

    return HttpResponse('<script>alert("下单成功");location.href="/buy/'+str(ob.id)+'"</script>')

def buy(request,oid):

    od = Order.objects.get(id=oid)
    # # good=Goods.objects.get(id=oid)
    # cart = request.session['cart']
    # good=cart[oid]
    # # print(od,type(od))
    context={'od':od}
    # for x in od:
    #     print(x)
    return render(request,'home/buy.html',context)
def pay(request):
    oid = request.POST.get('oid','')
    data = Order.objects.get(id=oid)
    data.status=2
    data.save()
    return HttpResponse('<script>alert("支付成功");location.href="/myorder"</script>')      
def myorder(request):
    id=request.session['VipUser']['uid']

    info= Order.objects.filter(uid_id=id)
    for a in info:
        a.sub=OrderInfo.objects.filter(orderid_id=a.id)
        # print(a.sub)
        for b in a.sub:
            b.sub=Goods.objects.get(id=b.gid_id)
    # return HttpResponse('ok')
    context={'info':info}
    return render(request,'home/myorder.html',context)
 

def login(request):
    if request.method == 'GET':
        return render(request,'home/login.html')
    else:
        try:
            ob = Users.objects.get(username=request.POST['username'])
            # 没被禁用的用户都可以登录
            if ob.status !='c':
                # 验证密码
                res = check_password(request.POST['password'],ob.password)
                # 判断密码是否正确
                if res:
                    # 登录成功,用户信息,记录到session,跳转地址
                    request.session['VipUser']={'uid':ob.id,'username':ob.username,'pic':ob.pic}
                    return  HttpResponse('<script>alert("登录成功");location.href="/newindex"</script>')
                else:
                    # 密码错误
                    raise
                    # return HttpResponse('密码错误')
        except:
            raise
        return HttpResponse('<script>alert("用户名或密码错误");location.href="/login"</script>')


# 注册
def register(request):
    return render(request,'home/register.html')
def doregister(request):
    username=request.GET.get('username')
    res = Users.objects.filter(username=username)
    if res:
        return HttpResponse(json.dumps('该用户名已被占用'))
    else:
        return HttpResponse(' ')

def dealregister(request):
    ob = Users()
    ob.username=request.POST['username']
    ob.password=request.POST['password']
    ob.sex=1
    ob.status='a'
    ob.save()
    return HttpResponse('<script>alert("注册成功");location.href="/login"</script>')



def member(request):
    ob=request.session['VipUser']
    db = Users.objects.get(id=ob['uid'])
    context={'user':db}
    return render(request,'home/member.html',context)
def infoedit(request,id):
    db=Users.objects.get(id=id)
    context={'userinfo':db}
    return render(request,'home/userinfoedit.html',context)
def userinfoupdate(request):
    db = Users.objects.get(id = request.POST['id'])
    db.username = request.POST['username']
    db.phone = request.POST['phone']

    
    db.pic = upload(request)

    db.save()
    return HttpResponse('<script>alert("修改成功");location.href="/member"</script>')

def upload(request):

    #执行图片的上传
    myfile = request.FILES.get("pic",None)
    print(myfile)
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open("./static/public/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()
    return '/static/public/pics/'+filename











